package com.kasax.ipcbus.corel;

import android.text.TextUtils;

import com.kasax.ipcbus.bean.Response;
import com.kasax.ipcbus.bean.ResponseBean;
import com.kasax.ipcbus.utils.GsonUtils;
import com.kasax.ipcbus.utils.LogUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class HermesInvocationHandler implements InvocationHandler {
    private final Class<CorelService> corelService;
    private final Class mClazz;

    public HermesInvocationHandler(Class<CorelService> corelServiceClass, Class clazz) {
        this.corelService = corelServiceClass;
        this.mClazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Response response = Hermes.getDefault().sendObjectRequest(corelService, mClazz, method, args);
        LogUtils.i(getClass(), "invoke response: " + response);
        if (!TextUtils.isEmpty(response.getData())) {
            ResponseBean responseBean = GsonUtils.fromJson(response.getData(), ResponseBean.class);
            Object responseBeanData = responseBean.getData();
            if (responseBeanData != null) {
                String json = GsonUtils.toJson(responseBeanData);
                LogUtils.i(getClass(), "invoke json: " + json);
                Class<?> returnType = method.getReturnType();
                Object obj = GsonUtils.fromJson(json, returnType);
                LogUtils.i(getClass(), "invoke obj: " + obj);
                return obj;
            }
        }
        return null;
    }
}
